package job.wuba;

import tools.Dict;
import tools.FormatTools;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;

import com.bj58.analysis.tools.CommonAnalysisToolsDriver;
import com.bj58.analysis.tools.LogToolsTag;
import com.bj58.analysis.tools.etl.bean.ETLTrackBean;
import com.bj58.analysis.track.format.TrackSplitUtils;
import com.bj58.analysis.track.format.TrackInputFormat;


public class WubaNetflowKeyEntry {
	public static Map<String, String> visitKeyMap2(List<String> lines,String statDate,String platform) throws Exception{
		Map<String, String> visitKeyMap = new HashMap<String, String>();
		ETLTrackBean trackInfo_0 = (ETLTrackBean)CommonAnalysisToolsDriver .parserToInstance(lines.get(0),LogToolsTag.TRACK_ETL_LOG);
		List<String> visitSourceList = FormatTools.getSourceFullPath(trackInfo_0, platform,2);
		int uv = 1;
		String vs = "0\t0\t0\t0\t0\t0\t0\t0";
		for(String line:lines)
		{
			ETLTrackBean trackinfo = (ETLTrackBean)CommonAnalysisToolsDriver .parserToInstance(line,LogToolsTag.TRACK_ETL_LOG);
			String newPageType = trackinfo.getPageType()!=null?trackinfo.getPageType():"";
			String url=trackinfo.getUrl();
			if(url.contains("sou.58.com") || url.contains("cast.58.com") || newPageType.equals("sou") ){
				continue;
			}
			//按session的第一条进行来源计算
			for (String visitsource : visitSourceList) {
				String key = statDate+"\t"+visitsource.replace(",", "\t");
				if(visitKeyMap.get(key)!=null){
					int pv = Integer.parseInt(visitKeyMap.get(key).split("\t")[0])+1;
					visitKeyMap.put(key, pv+"\t"+uv+"\t"+"0\t0\t0\t0\t0\t0"+"\001"+vs);
				}else{
					visitKeyMap.put(key, "1"+"\t"+uv+"\t"+"0\t0\t0\t0\t0\t0"+"\001"+vs);
				}
			}

		}

		return visitKeyMap;
	}

	public static Map<String, String> visitKeyMap(List<String> lines,String statDate,String platform) throws Exception{
		Map<String, String> visitKeyMap = new HashMap<String, String>();
		ETLTrackBean trackInfo_0 = (ETLTrackBean)CommonAnalysisToolsDriver .parserToInstance(lines.get(0),LogToolsTag.TRACK_ETL_LOG);
		ETLTrackBean trackInfo_end = (ETLTrackBean)CommonAnalysisToolsDriver .parserToInstance(lines.get(lines.size()-1),LogToolsTag.TRACK_ETL_LOG);
		List<String> visitSourceList = FormatTools.getSourceFullPath(trackInfo_0, platform,4);

		String startTime = trackInfo_0.getEpoch().split("\\.")[0];
		String endTime   = trackInfo_end.getEpoch().split("\\.")[0];
		Long timeOnSite=Long.parseLong(endTime)-Long.parseLong(startTime);

		int jump_out = 0;
		int uv = 1;
		int visit = 1;
		if(lines.size()==1){
			jump_out = 1;
		}
		//gautma 记录的是用户的访客数，以1开始，也就是说一个新用户在第一个session中，第一条日志的gautma值为1;在第二个session中为2以此类推；
		String gaUtma=trackInfo_0.getGautma();
		int visitCount=0;
		//从gaUtma中取出visitCount
		try{String[] gaUtmaArr=gaUtma.split("\\.");visitCount=Integer.parseInt(gaUtmaArr[5]);}catch(Exception e){visitCount=1;}
		int new_visit = visitCount==1?1:0;
		int isRepeat = visitCount>1?1:0;
		int new_uv=uv-isRepeat;

		for(String line:lines)
		{
			ETLTrackBean trackinfo = (ETLTrackBean)CommonAnalysisToolsDriver .parserToInstance(line,LogToolsTag.TRACK_ETL_LOG);
			String newPageType = trackinfo.getPageType()!=null?trackinfo.getPageType():"";
			String url=trackinfo.getUrl();
			if(url.contains("sou.58.com") || url.contains("cast.58.com") || newPageType.equals("sou") ){
				continue;
			}
			// trackinfo.getTkAreaPath() 和  trackinfo.getTkCatePath() 都为0,1,11 格式的数据
			String[] citys=FormatTools.formatString(trackinfo.getAreaPath());
			String[] cates=FormatTools.formatString(trackinfo.getCatePath());
			List<String> newCateList = new ArrayList<String>();
			for (String cid : cates) {
				newCateList.add(cid);
				if (cid.equals("8") || cid.equals("9")|| cid.equals("10")|| cid.equals("11")|| cid.equals("37031")) {
					newCateList.add("-101");
				} else if (cid.equals("13")|| cid.equals("14")|| cid.equals("15")) {
					newCateList.add("-102");
				}
			}

			List<String> bussFullPath=FormatTools.getFullPathList(FormatTools.getBussiness(FormatTools.formatString(trackinfo.getCatePath()),Dict.businessMap),1);
			String page = "";
			String trackurl = trackinfo.getTrackUrl();
			JSONObject object = JSONObject.fromObject(trackurl);

			if(object!=null && object.get("page")!=null){
				page = object.get("page").toString().equals("58kuaipaiztm")?"58kuaipaibaoming":object.get("page").toString();

			}

			/******处理page为58kuaipaibaoming的数据***************/
			if(page.equals("58kuaipaibaoming")){
				newPageType = "58kuaipaibaoming";
			}
			/******处理pageType为weidian的数据***************/
			if(newPageType.equals("weidian")){
				newPageType = page;
			}
			String[] pageTypeFullPath=FormatTools.getPageTypeFullPath(newPageType);
			//List<String> pvsourceList = FormatTools.getSourceFullPath(TrackObjectFormat.getTrackinfoByString(line),platform,4);
			for (String bussiness : bussFullPath) {
				for (String pageType : pageTypeFullPath) {
					for (String cityid : citys) {
						String area = StringUtils.isBlank(Dict.cityIdToNamePathMap.get(cityid))?"all\tall\tall\tall":Dict.cityIdToNamePathMap.get(cityid);
						cityid = area.equals("all\tall\tall\tall")?"0":cityid;
						for (String cateId : newCateList) {
							String cate =  StringUtils.isBlank(Dict.cateIdToNamePathMap.get(cateId))?"all\tall\tall\tall\tall":Dict.cateIdToNamePathMap.get(cateId);
							cateId = cate.equals("all\tall\tall\tall\tall")?"0":cateId;
							String vs = "0\t0\t0\t0\t0\t0\t0\t0";
							//按session的第一条进行来源计算
							for (String visitsource : visitSourceList) {
								String key = statDate+"\t"+bussiness+"\t"+pageType+"\t"+visitsource.replace(",", "\t")+"\t"+cityid+"\t"+cateId+"\t"+area+"\t"+cate;
								if(visitKeyMap.get(key)!=null){
									int pv = Integer.parseInt(visitKeyMap.get(key).split("\t")[0])+1;
									int jump_in = pv;//跳入数等于pv
									visitKeyMap.put(key, pv+"\t"+uv+"\t"+new_uv+"\t"+visit+"\t"+new_visit+"\t"+jump_in+"\t"+jump_out+"\t"+timeOnSite+"\001"+vs);
								}else{
									visitKeyMap.put(key, "1"+"\t"+uv+"\t"+new_uv+"\t"+visit+"\t"+new_visit+"\t"+"1"+"\t"+jump_out+"\t"+timeOnSite+"\001"+vs);
								}
							}
							//按每一条日志进行来源计算
//							for (String pvsource : pvsourceList) {
//								String key = statDate+"\t"+bussiness+"\t"+pageType+"\t"+pvsource.replace(",", "\t")+"\t"+cityid+"\t"+cateId+"\t"+area+"\t"+cate;
//								if(pvKeyMap.get(key)!=null){
//									//vs = pvKeyMap.get(key).split("\001")[0];
//									int pv = Integer.parseInt(pvKeyMap.get(key).split("\t")[0])+1;
//									int jump_in = pv;//跳入数等于pv
//									pvKeyMap.put(key, pv+"\t"+uv+"\t"+new_uv+"\t"+visit+"\t"+new_visit+"\t"+jump_in+"\t"+jump_out+"\t"+timeOnSite);
//								}else{
//									pvKeyMap.put(key, "1"+"\t"+uv+"\t"+new_uv+"\t"+visit+"\t"+new_visit+"\t"+"1"+"\t"+jump_out+"\t"+timeOnSite);
//								}
//							}

						}
					}
				}
			}

		}

		//---------------拼接key-------------------
//		String vs = "0\t0\t0\t0\t0\t0\t0\t0";
//		for (Map.Entry<String, String> entry : visitKeyMap.entrySet()) {
//			if(pvKeyMap.get(entry.getKey())!=null){
//				newKeyMap.put(entry.getKey(), entry.getValue()+"\001"+pvKeyMap.get(entry.getKey()));
//				pvKeyMap.remove(entry.getKey());
//			}else{
//				newKeyMap.put(entry.getKey(), entry.getValue()+"\001"+vs);
//			}
//
//		}
//		for (Map.Entry<String, String> entry : pvKeyMap.entrySet()) {
//			newKeyMap.put(entry.getKey(), vs+"\001"+entry.getValue());
//		}
		return visitKeyMap;
	}

	public static Map<String, String> uvKeyMap(List<List<String>> listLines,String statDate,String platform) throws Exception{
		Map<String, String> uvkeyMap = new HashMap<String, String>();

		for (List<String> list : listLines) {
				Map<String, String> visitkeyMap = visitKeyMap(list, statDate, platform);
				 for (Map.Entry<String, String> entry : visitkeyMap.entrySet()) {
					 String visitKey = entry.getKey();
					 String visitVal = entry.getValue();
					 String[] visitVal_1 = visitVal.split("\001")[0].split("\t");
					 String[] visitVal_2 = visitVal.split("\001")[1].split("\t");
					 if(uvkeyMap.get(visitKey)!=null){
						 String[] uvArrys_1 = uvkeyMap.get(visitKey).split("\001")[0].split("\t");
						 String[] uvArrys_2 = uvkeyMap.get(visitKey).split("\001")[1].split("\t");
						 int pv 				= Integer.parseInt(visitVal_1[0])+Integer.parseInt(uvArrys_1[0]);
						 int uv 				= visitVal_1[1].equals("1")?1:0;
						 int new_uv 			= 0;
						 if(Integer.parseInt(visitVal_1[2])==1&&listLines.size()==1){
							 new_uv = 1;
						 }
						 int visit 				= Integer.parseInt(visitVal_1[3])+Integer.parseInt(uvArrys_1[3]);
						 int new_visit 			= Integer.parseInt(visitVal_1[4])+Integer.parseInt(uvArrys_1[4]);
						 int jump_in 			= Integer.parseInt(visitVal_1[5])+Integer.parseInt(uvArrys_1[5]);
						 int jump_out 			= Integer.parseInt(visitVal_1[6])+Integer.parseInt(uvArrys_1[6]);
						 Long timeOnSite		= Long.parseLong(visitVal_1[7])+Long.parseLong(uvArrys_1[7]);

						 int first_pv 			= Integer.parseInt(visitVal_2[0])+Integer.parseInt(uvArrys_2[0]);
						 int first_uv 			= visitVal_2[1].equals("1")?1:0;
						 int first_new_uv 		= 0;
						 if(Integer.parseInt(visitVal_2[2])==1&&listLines.size()==1){
							 new_uv = 1;
						 }
						 int first_visit 		= Integer.parseInt(visitVal_2[3])+Integer.parseInt(uvArrys_2[3]);
						 int first_new_visit 	= Integer.parseInt(visitVal_2[4])+Integer.parseInt(uvArrys_2[4]);
						 int first_jump_in 		= Integer.parseInt(visitVal_2[5])+Integer.parseInt(uvArrys_2[5]);
						 int first_jump_out 	= Integer.parseInt(visitVal_2[6])+Integer.parseInt(uvArrys_2[6]);
						 Long first_timeOnSite 	= Long.parseLong(visitVal_2[7])+Long.parseLong(uvArrys_2[7]);

						 String str_1 = pv+"\t"+uv+"\t"+new_uv+"\t"+visit+"\t"+new_visit+"\t"+jump_in+"\t"+jump_out+"\t"+timeOnSite;
						 String str_2 = first_pv+"\t"+first_uv+"\t"+first_new_uv+"\t"+first_visit+"\t"+first_new_visit+"\t"+first_jump_in+"\t"+first_jump_out+"\t"+first_timeOnSite;
						 uvkeyMap.put(visitKey, str_1+"\001"+str_2);
					 }else{
						 uvkeyMap.put(visitKey, visitVal);
					 }
				 }
			}

		return uvkeyMap;
	}


}
